package com.circle.rest.core.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.circle.rest.core.common.model.ErrorResponseData;
import com.circle.rest.core.util.RedisUtil;
import com.circle.rest.core.util.ToolUtil;
import com.circle.rest.modular.sys.model.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            if (!checkUrl(request)) {
                String token = request.getHeader("Authorization");
                if (ToolUtil.isEmpty(token)) {
                    response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_FORBIDDEN, "没有提供Token")));
                    return;
                }
                String header = token.substring(0, 10);
                if (!header.toLowerCase().startsWith("bearer ")) {
                    response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_FORBIDDEN, "Token格式错误")));
                    return;
                }
                //检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回
                Map<String, Object> map = JwtUtil.validateToken(token);

                String json = map.get("user").toString();
                User user = JSONObject.parseObject(json, User.class);
                Object o = RedisUtil.get("JWT-TOKEN:" + user.getId());
                if (o != null) {
                    if (!o.toString().equals(token.replace("Bearer ", ""))) {
                        response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_UNAUTHORIZED, "已在其他设备登录，请重新登录！")));
                        return;
                    }
                } else {
                    response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_UNAUTHORIZED, "Token过期")));
                    return;
                }

            }
        } catch (ExpiredJwtException e) {
            response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_UNAUTHORIZED, "Token过期")));
            return;
        } catch (SignatureException e) {
            response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_FORBIDDEN, "Token无效")));
            return;
        } catch (MalformedJwtException e) {
            response.getWriter().write(JSON.toJSONString(new ErrorResponseData(HttpServletResponse.SC_FORBIDDEN, "Token格式错误")));
            return;
        }
        //如果jwt令牌通过了检测, 那么就把request传递给后面的RESTful api
        filterChain.doFilter(request, response);
    }

    private boolean checkUrl(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        if (servletPath.contains("swagger-")
                || servletPath.contains("api-docs")
                || servletPath.contains("websocket")
                || servletPath.contains("favicon")) {
            return true;
        }
        if (pathMatcher.match("/sys/user/login", servletPath)
                || pathMatcher.match("/swagger-ui", servletPath)
                || pathMatcher.match("/sys/log/export", servletPath)
                || pathMatcher.match("/druid", servletPath)) {
            return true;
        }
        return false;
    }

}